package com.smart.manager.wiki.entities.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.manager.wiki.entities.body.RDocStrategy;
import com.smart.manager.wiki.entities.models.WikiDocStrategy;
import com.smart.manager.wiki.entities.models.query.QWikiDocStrategy;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class DocStrategyRepository {


    public Page<WikiDocStrategy> pageList(RDocStrategy.SearchBody search) {
        QWikiDocStrategy query = new QWikiDocStrategy();
        Opt.ofBlankAble(search.getTitle()).ifPresent(x -> query.title.contains(x));
        query.order().sort.asc().order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<WikiDocStrategy>().load(query.findPagedList());
    }






    public void add(RDocStrategy.EditBody body) {
        BeanUtil.copyProperties(body, WikiDocStrategy.class).setReadCount(0).save();
    }


    public void update(Long id, RDocStrategy.EditBody body) {
        QWikiDocStrategy query = new QWikiDocStrategy();
        WikiDocStrategy record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, "修改失败:攻略数据不存在或已被删除");
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
    }

    public int delByIds(List<Long> ids) {
        List<WikiDocStrategy> list = new QWikiDocStrategy().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        return DB.deleteAll(list);
    }


    /**
     * @param checkNull 是否检查空值
     * @param addCount  是否增加阅读次数
     * @param id 攻略ID
     * @return {@code WikiDocStrategy}
     */
    public WikiDocStrategy readOne(Long id, Boolean checkNull, boolean addCount) {
        WikiDocStrategy strategyEssay = new QWikiDocStrategy().id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(strategyEssay, "攻略文件不存在");
        if (addCount) {
            strategyEssay.setReadCount(strategyEssay.getReadCount() + 1);
            strategyEssay.update();
        }
        return strategyEssay;

    }


}
